package com.sxf.mybatis.interceptor;

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.RowBounds;

import com.sxf.mybatis.help.ExRowBounds;
import com.sxf.mybatis.help.QueryType;

/**
 * 处理ResultSetHandler拦截器(如果只取统计数据,则只返回统计数据)
 * 
 * @author SXF
 * 
 */
@Intercepts({ @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = { Statement.class }) })
public class ProcessResultSetHandlerInterceptor implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		ResultSetHandler rHandler = (ResultSetHandler) invocation.getTarget();
		MetaObject metaObject = SystemMetaObject.forObject(rHandler);
		RowBounds rowBounds = (RowBounds) metaObject.getValue("rowBounds");

		Object[] objArr = invocation.getArgs();
		Statement statement = null;
		if (objArr != null) {
			statement = (Statement) objArr[0];
		}

		ExRowBounds erb = null;
		QueryType queryType = QueryType.OBJECT;
		if (rowBounds instanceof ExRowBounds) {
			erb = (ExRowBounds) rowBounds;
			queryType = erb.getQueryType();
		}

		Object rObj = null;
		switch (queryType) {
		case NUMBER: {
			ResultSet rs = statement.getResultSet();
			if (rs != null && rs.next()) {
				erb.setCount(rs.getLong(1));
				rs.close();
				statement.close();
			}
			break;
		}
		default: {
			rObj = invocation.proceed();
		}
		}
		return rObj;
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {

	}

}
